package com.tongji.housediy.view.components
{
	import com.tongji.housediy.events.commonEvent.ExchangeDataEvent;
	import com.tongji.housediy.events.commonEvent.RelatedRoomAdminEvent;
	import com.tongji.housediy.events.commonEvent.RoomNameAdminEvent;
	import com.tongji.housediy.events.commonEvent.RotationRelatedEvent;
	import com.tongji.housediy.events.commonEvent.RulerAdminEvent;
	import com.tongji.housediy.events.commonEvent.SetCompStateEvent;
	import com.tongji.housediy.events.commonEvent.ShowHideFilterEvent;
	import com.tongji.housediy.events.commonEvent.ShowHideTitleWindowEvent;
	import com.tongji.housediy.utils.AbsorptionDetection;
	import com.tongji.housediy.utils.CollisionDetection;
	import com.tongji.housediy.utils.ConstVariableInventory;
	import com.tongji.housediy.utils.DragDropManager;
	import com.tongji.housediy.utils.MathCalculation;
	import com.tongji.housediy.vo.Goods;
	import com.tongji.housediy.vo.PicModel;
	
	import de.polygonal.ds.DListNode;
	
	import flash.display.BitmapData;
	import flash.display.BlendMode;
	import flash.display.DisplayObject;
	import flash.display.GraphicsBitmapFill;
	import flash.display.GraphicsPath;
	import flash.display.GraphicsPathCommand;
	import flash.display.GraphicsSolidFill;
	import flash.display.IGraphicsData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.ui.Mouse;
	import flash.ui.MouseCursor;
	import flash.utils.ByteArray;
	
	import mx.controls.Image;
	import mx.core.DragSource;
	import mx.core.IFlexDisplayObject;
	import mx.core.IUIComponent;
	import mx.core.UIComponent;
	import mx.events.DragEvent;
	import mx.managers.DragManager;
	
	import spark.filters.GlowFilter;
	
	/**
	 * 这个类用来绘制 地板，继承自 RoomShape
	 * @author chenchao
	 * 
	 */	
	public class RoomFloor extends RoomShape
	{
		private var graphicsData:Vector.<IGraphicsData>;
		public var stroke:IGraphicsData;
		private var commands:Vector.<int>;
		
		private var acceptAllFormat:Array = ["wallFormat", "independentFloor", "furnitureFormat", "mapFormat"];
		
		public var borderLength:int;
		private var curveVector:Vector.<int>;
		
		public var materialBitmapData:BitmapData;
		
		private var parentRoomBoundingBox:Rectangle;
		
		// 保存图片路径，供 保存打开 功能使用
		public var dragPicSrc:String;
		
		public function RoomFloor(data:Vector.<Number>, curveVector:Vector.<int>, borderLength:int, roomType:String)
		{
			super(data);
			
			this.borderLength = borderLength;
			this.curveVector = curveVector;
			
			var mapData:BitmapData;
			if (roomType == "room")
			{
				mapData = ConstVariableInventory.roomBitmapData;
				this.hostGoods = ConstVariableInventory.initialRoomGoods;
			}
			else if (roomType == "independentFloor")
			{
				mapData = ConstVariableInventory.floorBitmapData;
				this.hostGoods = ConstVariableInventory.initialFloorGoods;
			}
			
			this.selectedColorID = this.hostGoods.selectedColorID;
			this.selectedSizeID = this.hostGoods.selectedSizeID;
			this.dragPicSrc = this.hostGoods.dragPicSrc;
			
			materialBitmapData = mapData;
			stroke = new GraphicsBitmapFill(mapData);
			
			draw();
			
			// 侦听内墙和家具的拖拽事件
			this.addEventListener(DragEvent.DRAG_ENTER, dragEnterInRoomHandler);
			this.addEventListener(DragEvent.DRAG_DROP, dragDropInRoomHandler);
			this.addEventListener(DragEvent.DRAG_EXIT, dragExitFromRoomHandler);			
		}

		/**
		 * Expand Room 的时候需要重绘房间
		 * data 数据因为共享 AbstactDrawingRoom 类中的 vertices，所以不需要重置
		 * @param borderLength Expand Room 之后房间边框的数量，draw() 的时候需要用到
		 * 
		 */		
		public function reDraw(borderLength:int):void
		{
			this.borderLength = borderLength;
			draw();
		}
		
		/**
		 *  隐藏显示出来的所有顶点（Vertex）
		 * 
		 */		
		public function hideVertex():void
		{
			for (var i:int = 0; i < this.numChildren; i++)
			{
				if (this.getChildAt(i) is InteriorWall || this.getChildAt(i) is IndependentFloor)
					(this.getChildAt(i) as AbstractDrawingRoom).hideVertex();
			}
		}
		
		override public function changeSizeAndColor(picModel:PicModel, bitmapData:BitmapData = null, hostGoods:Goods = null):void
		{
			if (hostGoods)
				this.hostGoods = hostGoods;
			
			this.materialBitmapData = bitmapData;
			this.selectedColorID = picModel.selectedColorID;
			this.selectedSizeID = picModel.selectedSizeID;
			this.dragPicSrc = picModel.dragPicSrc;
			stroke = new GraphicsBitmapFill(bitmapData);
			draw();
		}
		
		override protected function draw():void
		{
			this.graphics.clear();
			
			commands = new Vector.<int>();
			commands.push(GraphicsPathCommand.MOVE_TO);
			
			var count:int = 0;
			
			for (var i:int = 0; i < borderLength; i++)
			{
				if (curveVector.indexOf(count) != -1)
				{
					commands.push(GraphicsPathCommand.CURVE_TO);
					count += 2;
				}
				else
				{
					commands.push(GraphicsPathCommand.LINE_TO);
					count += 1;
				}
			}
			
			var path:GraphicsPath = new GraphicsPath(commands, data);
			
			graphicsData = new Vector.<IGraphicsData>();
			graphicsData.push(stroke);
			graphicsData.push(path);
			
			this.graphics.lineStyle(0.6, 0xffff00, 0);
			this.graphics.drawGraphicsData(graphicsData);
		}
		
		override protected function mouseDownHandler(event:MouseEvent):void
		{
			///////////////////////by zazisb
			AbsorptionDetection.CancelAbsorption(this);
			
			super.mouseDownHandler(event);
			
			// 隐藏标尺
			this.dispatchEvent(new RulerAdminEvent(RulerAdminEvent.HIDE_ALL_RULERS));
			// 隐藏 RoomName
			this.dispatchEvent(new RoomNameAdminEvent(RoomNameAdminEvent.HIDE_ROOM_NAME));
			
			(this.parent as AbstractDrawingRoom).hideVertex();
			
			// 如果需要拖拽该 地板 从外部至房间内的话，设置其 index
			if (this.parent is IndependentFloor && this.parent.parent is GridContainer)
				this.parent.parent.setChildIndex(this.parent, this.parent.parent.numChildren - 1);
			
			// 获取父房间类包围盒
			if (this.parent is IndependentFloor && this.parent.parent.parent is AbstractDrawingRoom)
				parentRoomBoundingBox = (this.parent.parent.parent as AbstractDrawingRoom).updateBoundingAndCenterPoint();
		}
		
		override protected function mouseUpHandler(event:MouseEvent):void
		{
			super.mouseUpHandler(event);
			
			// 如果选择的地板为自定义地板，则显示 RotationBtn
			/*if (this.parent is IndependentFloor)
			{
				showRotationBtn();
			}*/
			
			// 如果拖拽的是 IndependentFloor，那么 MouseUp 的时候需要判断是否在 Room 内
			if (this.parent is IndependentFloor)
			{
				(this.parent as AbstractDrawingRoom).updateBoundingAndCenterPoint();
				
				/*trace((this.parent as AbstractDrawingRoom).parentGridContainer.mouseX, (this.parent as AbstractDrawingRoom).parentGridContainer.mouseY);
				/*trace((this.parent as AbstractDrawingRoom).boundingRec.x, (this.parent as AbstractDrawingRoom).boundingRec.y);*/
				/*trace(this.parent.mouseX, this.parent.mouseY);*/
	
				
				if (this.parent.parent.parent is AbstractDrawingRoom)
				{
				/*(this.parent as AbstractDrawingRoom).parentGridContainer.setRoomPosition(this.parent as IndependentFloor,
					//(this.parent as AbstractDrawingRoom).parentGridContainer.contentMouseX - this.parent.mouseX,
					(this.parent as AbstractDrawingRoom).x,
					//(this.parent as AbstractDrawingRoom).parentGridContainer.contentMouseY - this.parent.mouseY,
					(this.parent as AbstractDrawingRoom).y,
					//(this.parent as AbstractDrawingRoom).parentGridContainer.mouseX - (this.parent as AbstractDrawingRoom).x,
					//(this.parent as AbstractDrawingRoom).parentGridContainer.mouseY - (this.parent as AbstractDrawingRoom).y);
					this.parent.mouseX,
					this.parent.mouseY);*/
				}
				else
				{
					(this.parent as AbstractDrawingRoom).parentGridContainer.setRoomPosition(this.parent as IndependentFloor,
						//(this.parent as AbstractDrawingRoom).parentGridContainer.contentMouseX - this.parent.mouseX,
						(this.parent as AbstractDrawingRoom).x,
						//(this.parent as AbstractDrawingRoom).parentGridContainer.contentMouseY - this.parent.mouseY,
						(this.parent as AbstractDrawingRoom).y,
						(this.parent as AbstractDrawingRoom).parentGridContainer.mouseX - (this.parent as AbstractDrawingRoom).x,
						(this.parent as AbstractDrawingRoom).parentGridContainer.mouseY - (this.parent as AbstractDrawingRoom).y);
				}
			}
			
			// 显示 TitleWindow
			if (Mouse.cursor != MouseCursor.IBEAM)
				dispatchShowInfoEvent();

			/////////////////////////////by zazisb 保存碰撞关联的房间
			
			AbsorptionDetection.DoAbsorption(this);
		}
		
		override protected function enterFrameHandler(event:Event):void
		{
			this.dispatchEvent(new RotationRelatedEvent(RotationRelatedEvent.HIDE_ROTATION_BTN));
			this.dispatchEvent(new ShowHideTitleWindowEvent(ShowHideTitleWindowEvent.HIDE_TITLE_WINDOW));
			
			super.enterFrameHandler(event);
			
			if (this.parent is IndependentFloor)
			{
				(this.parent).x += this.offsetX;
				(this.parent).y += this.offsetY;
				
				if (this.parent.parent.parent is AbstractDrawingRoom)
				{
					if (CollisionDetection.isCollisionWithOther(this.parent as IndependentFloor)
						|| ((this.parent.parent.parent as AbstractDrawingRoom).updateBoundingAndCenterPoint().width != parentRoomBoundingBox.width)
						|| ((this.parent.parent.parent as AbstractDrawingRoom).updateBoundingAndCenterPoint().height != parentRoomBoundingBox.height))
					{
						(this.parent).x -= this.offsetX;
						(this.parent).y -= this.offsetY;
					}
				}
				else
				{
					if (CollisionDetection.isCollisionWithOther(this.parent as IndependentFloor))
					{
						(this.parent).x -= this.offsetX;
						(this.parent).y -= this.offsetY;
					}
				}
			}
			else
			{
				var tempRoomX:Number = (this.parent as AbstractDrawingRoom).x;
				var tempRoomY:Number = (this.parent as AbstractDrawingRoom).y;
				
				var isX:Boolean = false;
				var isY:Boolean = false;
				
				if (offsetX != 0)
				{
					(this.parent).x += this.offsetX;
					
					if (CollisionDetection.isCollision(this))
						isX = true;
					
					(this.parent).x = tempRoomX;
				}
				
				if (offsetY != 0)
				{
					(this.parent).y += this.offsetY;
					
					if (CollisionDetection.isCollision(this))
						isY = true;
					
					(this.parent).y = tempRoomY;
				}
				
				if (!isX && !(this.parent as AbstractDrawingRoom).parentGridContainer.isYKeyDown)
					(this.parent).x += this.offsetX;
				if (!isY && !(this.parent as AbstractDrawingRoom).parentGridContainer.isXKeyDown)
					(this.parent).y += this.offsetY;
			}
		}
		
		override public function moveShape(xOffset:Number = 0, yOffset:Number = 0):Boolean
		{
			(this.parent).x += xOffset;
			(this.parent).y += yOffset;
			
			if (this.parent is IndependentFloor)
			{
				if (CollisionDetection.isCollisionWithOther(this.parent as IndependentFloor))
				{
					(this.parent).x -= xOffset;
					(this.parent).y -= yOffset;
					return false;
				}
				else
					return true;
			}
			else
			{
				if (CollisionDetection.isCollision(this))
				{
					(this.parent).x -= xOffset;
					(this.parent).y -= yOffset;
					return false;
				}
				else
					return true;
			}
		}
		
		// 显示 RotationBtn
		/*private function showRotationBtn():void
		{
			var parentRoom:AbstractDrawingRoom = this.parent as AbstractDrawingRoom;
			
			var rectangle:Rectangle = parentRoom.updateBoundingAndCenterPoint();
			
			var initialX:Number = rectangle.width / 2 - 11.5 + rectangle.x;
			var initialY:Number = rectangle.height + 20 + rectangle.y;
			
			this.dispatchEvent(new RotationRelatedEvent(RotationRelatedEvent.SHOW_ROTATION_BTN, initialX, initialY, parentRoom));
		}*/
		
		private function dragEnterInRoomHandler(event:DragEvent):void
		{
			if (!(this.parent is IndependentFloor) && acceptAllFormat.indexOf(event.dragSource.formats[0]) != -1)
			{
				DragManager.acceptDragDrop(IUIComponent(event.target));
				if (event.dragSource.formats[0] != "mapFormat")
					this.addEventListener(DragEvent.DRAG_OVER, roomFloorDragOverHandler);
			}
			else if (this.parent is IndependentFloor && event.dragSource.formats[0] == "mapFormat")
			{
				DragManager.acceptDragDrop(IUIComponent(event.target));
			}
		}
		
		private function roomFloorDragOverHandler(event:DragEvent):void
		{
			var collisionObj:DisplayObject = event.dragSource.dataForFormat(event.dragSource.formats[0]) as DisplayObject;
			
			if (isCollision(collisionObj))
				DragManager.showFeedback(DragManager.NONE);
			else
				DragManager.showFeedback(DragManager.MOVE);
		}
		
		private function isCollision(collisionObj:DisplayObject):Boolean
		{
			var parentRoom:AbstractDrawingRoom = this.parent as AbstractDrawingRoom;
			
			var currentNode:DListNode = parentRoom.borderVertexList.head;
			while (currentNode.next != parentRoom.borderVertexList.head)
			{
				currentNode = currentNode.next;
				if (currentNode.data is RoomBorder)
				{
					if (CollisionDetection.complexHitTestObject(collisionObj, (currentNode.data as RoomBorder).drawShape))
						return true;
				}
			}
			
			if (!(collisionObj is IndependentFloor))
			{
				for (var i:int = 0; i < numChildren; i++)
				{
					if (!(this.getChildAt(i) is IndependentFloor) && CollisionDetection.complexHitTestObject(collisionObj, this.getChildAt(i)))
						return true;
				}
			}
			
			return false;
		}
		
		private function dragDropInRoomHandler(event:DragEvent):void
		{
			this.removeEventListener(DragEvent.DRAG_OVER, roomFloorDragOverHandler);
			
			if (event.dragSource.formats[0] == "mapFormat")
			{
				this.hostGoods = event.dragSource.dataForFormat(event.dragSource.formats[0])[1] as Goods;
				this.selectedColorID = this.hostGoods.selectedColorID;
				this.selectedSizeID = this.hostGoods.selectedSizeID;
				this.dragPicSrc = this.hostGoods.dragPicSrc;
				
				materialBitmapData = event.dragSource.dataForFormat(event.dragSource.formats[0])[0] as BitmapData;
				stroke = new GraphicsBitmapFill(event.dragSource.dataForFormat(event.dragSource.formats[0])[0] as BitmapData);
				draw();
			}
			else
			{
				var floorChild:DisplayObject = event.dragSource.dataForFormat(event.dragSource.formats[0]) as DisplayObject;
				floorChild.scaleX = 1;
				floorChild.scaleY = 1;
				floorChild.x = mouseX;
				floorChild.y = mouseY;
				
				if (floorChild is IndependentFloor)
					addChildAt(floorChild, 0);
				else
					addChild(floorChild);
				
				// 如果拖拽进来的是 InteriorWall 或者 IndependentFloor，那么给其 parentGridContainer 属性赋值
				if (floorChild is InteriorWall || floorChild is IndependentFloor)
				{
					(floorChild as AbstractDrawingRoom).parentGridContainer = this.parent.parent as GridContainer;
				}
			}
		}
		
		private function dragExitFromRoomHandler(event:DragEvent):void
		{
			this.removeEventListener(DragEvent.DRAG_OVER, roomFloorDragOverHandler);
		}
		
		private function dispatchShowInfoEvent():void
		{
			var rectangle:Rectangle;
			var windowPoint:Point;
			
			if (this.parent.parent is GridContainer)
				rectangle = this.getRect(this.parent.parent);
			else
				rectangle = this.getRect(this.parent.parent.parent.parent);
				
			var secondPoint:Point = new Point(rectangle.x + rectangle.width / 2 + rectangle.width / 3, rectangle.y + rectangle.height / 2 - rectangle.height / 3);
			
			if (this.parent.parent is GridContainer)
				windowPoint = this.parent.parent.localToGlobal(secondPoint);
			else
				windowPoint = this.parent.parent.parent.parent.localToGlobal(secondPoint);
			
			this.dispatchEvent(new ShowHideTitleWindowEvent(ShowHideTitleWindowEvent.SHOW_TITLE_WINDOW,
				rectangle.x + rectangle.width / 2, rectangle.y + rectangle.height / 2,
				secondPoint.x, secondPoint.y,
				windowPoint.x, windowPoint.y,
				this));
			this.dispatchEvent(new ShowHideFilterEvent(ShowHideFilterEvent.SHOW_FILTER, this));
		}
	}
}